import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.DateFormat;
import java.util.Calendar;
import java.util.Date;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;


public class PruebaCommons {

	public static void main(String[] args) {
		
		FTPClient ftp = null;
		String fecha = "2010.05.25";
		
		try
	    {
		  String server = "e4ftl01.cr.usgs.gov";
		  String folder = "/MOLT/MOD09Q1.005/";
		  folder = folder.concat(fecha).concat("/");
		  String destinationFolder = System.getProperty("user.dir");
		  Calendar start = Calendar.getInstance();
		  start.set(Calendar.YEAR, 1990);
		  Calendar end = Calendar.getInstance();
		  
	      // Connect and logon to FTP Server
	      ftp = new FTPClient();
	      ftp.connect(server);
	      ftp.login( "anonymous", "password" );
	      System.out.println("Connected to " + server + ".");
	      System.out.print(ftp.getReplyString());

	      // List the files in the directory
	      ftp.changeWorkingDirectory( folder );
	      FTPFile[] files = ftp.listFiles();
	      System.out.println( "Number of files in dir: " + files.length );
	      DateFormat df = DateFormat.getDateInstance( DateFormat.SHORT );
	      for( int i=0; i<files.length; i++ )
	      {
	        Date fileDate = files[ i ].getTimestamp().getTime();
	        if( fileDate.compareTo( start.getTime() ) >= 0 &&
	          fileDate.compareTo( end.getTime() ) <= 0 )
	        {
	          // Download a file from the FTP Server
	          System.out.print( df.format( files[ i ].getTimestamp().getTime() ) );
	          System.out.println( "\t" + files[ i ].getName() );
	          File file = new File( destinationFolder + File.separator + files[ i ].getName() );
	          FileOutputStream fos = new FileOutputStream( file ); 
	          ftp.retrieveFile( files[ i ].getName(), fos );
	          fos.close();
	          file.setLastModified( fileDate.getTime() );
	        }
	      }

	      // Logout from the FTP Server and disconnect
	      ftp.logout();
	      ftp.disconnect();

	    }catch( Exception e ){
	      e.printStackTrace();
	    }finally {
	        if(ftp.isConnected()) {
	            try {
	              ftp.disconnect();
	            } catch(IOException ioe) {
	              // do nothing
	            }
	          }
        }



	}

}
